package com.grz.springbootdemo.core;

import com.alibaba.fastjson2.JSONObject;
import com.grz.domain.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.Method;


@Component
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("preHandle1");
        // 返回值 true 代表可以继续请求，如果为false，拒绝请求
//        response.setContentType("application/json;charset=utf-8");
        // {"code":401,"msg":"请先登录"}
//        response.getWriter().write("{\"code\":401,\"msg\":\"请先登录\"}");
        // 1.获取到什么信息?
        // request \ response \ session
        HttpSession session = request.getSession();
        User currentLoginUser = (User) session.getAttribute("currentLoginUser");
        if (currentLoginUser == null) {
            // 没登陆
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(Result.error(401, "请先登录！")));
            return false;
        }

        // 获取要执行的方法，或者要执行的Controller
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            HasUsername hasUsername = method.getAnnotation(HasUsername.class);
            if (hasUsername != null) {
                // 需要根据用户名判断
                // 可以从session中获取当前访问用户的角色，进而判断
                if (currentLoginUser.getUsername().equals(hasUsername.value())) {
                    return true;
                } else {
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write(JSONObject.toJSONString(Result.error(403, "您没有操作权限，请联系管理员！")));
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("postHandle1");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("afterCompletion1");
    }
}